package com.june.spider.controller;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import com.june.spider.exception.URLNotFoundException;
import com.june.spider.exception.WebsiteNotFoundException;
import com.june.spider.model.LiveVideoRoom;
import com.june.spider.service.SpiderService;

@Controller
public class IndexController {
	
	private static final String ERR_MSG = "errMsg";

	private static final String INDEX = "index";

	private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private SpiderService spiderService;
	
	@GetMapping({"/", "index"})
	public String index() {
		return INDEX;
	}
	
	@GetMapping("rooms")
	public String rooms(String url, Model model) {
		if (!StringUtils.hasText(url)) {
			model.addAttribute(ERR_MSG, "请输入直播平台网址");
			return INDEX;
		}
		List<LiveVideoRoom> rooms = spiderService.getRoomList(url);
		model.addAttribute("rooms", rooms);
		model.addAttribute("url", url);
		if (rooms.isEmpty()) {
			model.addAttribute(ERR_MSG, "未找到相关直播列表数据");
		}
		return INDEX;
	}
	
	@ExceptionHandler
	public ModelAndView resolveException(WebsiteNotFoundException e) {
		return renderError(Optional.ofNullable(e.getMessage()).orElse("未找到相关直播列表数据"));
	}
	
	@ExceptionHandler
	public ModelAndView resolveException(URLNotFoundException e) {
		return renderError(Optional.ofNullable(e.getMessage()).orElse("输入的网址为空或格式不正确"));
	}

	@ExceptionHandler
	public ModelAndView resolveException(Exception e) {
		LOGGER.error(e.getMessage(), e);
		return renderError("数据获取失败，请稍候再试");
	}
	
	private ModelAndView renderError(String errMsg) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject(ERR_MSG, errMsg).setViewName(INDEX);
		return modelAndView;
	}
	
}
